<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
  <title>聊天</title>
  <link rel="stylesheet" type="text/css" href="index.css">
  <script src="jquery-1.12.4.min.js"></script>
  <script src="/socket.io/socket.io.js"></script>
</head> 
<body>
<div class="box">
  <div class="box-left">
    <div id="userBox">
        <div class="users heMsg active" id="qun" user-id="qunid">
          <a href="javascript:;" class="headImg">
            <span class="info_num"></span>
            <img src="b.png" alt="" style="height: 100%;width: 100%;">
          </a>
          <div class="infocont">五胡四海群</div>
        </div>   
        <div id="user">
          <!-- <div class="user heMsg">
            <a href="javascript:;" class="headImg">
              <span class="info_num"></span>
              <img src="imgs/a.png" alt="" style="height: 100%;width: 100%;">
            </a>
            <div class="infocont">五胡四海群</div>
          </div>    --> 
        </div>    
    </div>
  </div>
  <div class="box-right">
    <div class="content-title">
      <h5 id="h5">五胡四海群</h5>
      <button id="login">登录</button>
      <button id="username" style="display: none">名字</button>
      <input type="" id="name" maxlength="6" onblur="window.scroll(0,0)">
    </div>
    <div class="content">
      <div class="msgBox" id="msgBox">
        <!-- 对方消息 -->
        <!-- <div class="heMsg">
          <div class="msg-list-name">asdf</div>
          <a href="javascript:;" class="headImg">
            <img src="imgs/a.png" alt="" style="height: 100%;width: 100%;">
          </a>
          <span class="jiantou"></span>
          <div class="infocont">saadssadsss</div>
        </div> -->
        <!-- 时间提示消息 -->
        <!-- <div class="tipinfo">
          <span>2016-06-21 16:52:12</span>
        </div> -->
        <!-- 我发的消息 -->
        <!-- <div class="myMsg">
          <div class="msg-list-name">asdf</div>
          <a href="javascript:;" class="headImg">
            <img src="imgs/a.png" alt="" style="height: 100%;width: 100%;">
          </a>
          <span class="jiantou"></span>
          <div class="infocont">dsadssadssadssadsdss</div>
        </div> -->
      </div>
      <div class="msgBottom"> 
        <div class="add-select-box">
          <div class="file_btns">
            <span class="tupian_btn">
              <input type="file" onchange="sendFile(this)" accept="image/*">
            </span>
            <span class="yinyue_btn">
              <input type="file" onchange="sendFile(this)" accept="audio/*">
            </span>
            <span class="shiping_btn">
              <input type="file" onchange="sendFile(this)" accept="video/*"> 
            </span>
          </div>
          <!-- <span class="emoji"></span> -->
        </div>
        <button class="bot-btn" id="fileBtn"></button>
        <div contenteditable="true" class="editdiv" id="text" placeholder="请输入......"></div>
        <a href="javascript:;" class="bot-btn send" id="send">发送</a>
      </div>
    </div>
  </div>  
</div>
<!-- 图片查看器 -->
<div id="lookimg">
  <div>
    <img src="loading.png" alt="">  
  </div>
</div>
<script>
document.execCommand("defaultParagraphSeparator", false, "div");    //编辑器兼容处理
var URL = window.URL || window.webkitURL;    //兼容写法
localStorage.clear(); //清除所有数据
var socket,myName,myId,nowId="qunid",nowName="五湖四海群";


// 表情相关
var emojis = [];
var filsPanel = $(".add-select-box");
for(var i=0;i<52;i++){
  emojis.push(`<img src="emoji/${i+1}.png" onclick="insetImg('emoji/${i+1}.png')">`)
}
filsPanel.prepend(emojis.join(''));      //渲染表情
$("#fileBtn").click(function(){  //表情显示与影藏
  filsPanel.slideToggle(200)
  if(Isfocus){
    $("#text").focus();
  }
})
$("#msgBox").click(function(){       //表情显示与影藏
  filsPanel.slideUp(200)
})
function insetImg(url){              //插入表情
  document.execCommand('InsertImage', false, url); 
}
var Isfocus = false,timer;           //用于控制软键盘
$("#text").on('focus',function(){
  Isfocus = true;
  clearTimeout(timer);

})
$("#text").on('blur',function(){
  timer = setTimeout(()=>{
    Isfocus=false;
    window.scrollTo(0, 0); //ios 微信浏览器中失去焦点回滚
  },300)
})


//连接即时通讯操作
function link(data){
  socket = io('http://localhost:3000'); 
  // socket = io('http://172.27.35.1:3000/');  
  //连接成功时触发
  socket.on('connect',function(){
     console.log('建立连接成功');
     myId = data.id = socket.id;
     socket.emit('login', data, function(arr){
        login(arr);
     });
     console.log('登录信息',data);
  })  
  //登录事件
  socket.on('login',function(data){
    console.log("其他人登录信息",data)
    $('#user').append(`
      <div class="user heMsg" user-id="${data.id}">
        <a href="javascript:;" class="headImg">
          <span class="info_num"></span>
          <img src="a.png" alt="" style="height: 100%;width: 100%;">
        </a>
        <div class="infocont">${data.name}</div>
      </div>   
    `);
    $("#msgBox").append(`
      <div class="tipinfo">
        <span>${timeF()} <b>${data.name}</b> 上线了!</span>
      </div>
    `);
    $("#h5").html("五湖四海群("+($('.user').length+1)+")");
  })
  //退出事件
  socket.on('out',function(data){  console.log('其他人退出信息',data)
    var id = data.id;
    $(".user").each(function(){
      if($(this).attr("user-id") == id){
        $(this).remove()
      } 
    })
    $("#msgBox").append(`
      <div class="tipinfo">
        <span>${timeF()} <b>${data.name}</b> 下线了!</span>
      </div>
    `)
    $("#h5").html("五湖四海群("+($('.user').length+1)+")");
  })
  // 接受消息
  socket.on('msg',function(data){
    var html = msgTPL(data,true);
    if(data.to == 'qunid'){
       data.to = data.from;
       data.toName = data.fromName;
       data.from = 'qunid';
       data.fromName = '五胡四海群';
    }
    if(data.from == nowId){   //个人
      $("#msgBox").append(html).scrollTop(100000);
    }else{
      $('[user-id='+data.from+']').find('.info_num').show();
    }
    var DB = localStorage.getItem(myId+'-'+data.from) || '';
    localStorage.setItem(myId+'-'+data.from, DB+html);
  })

  //断开连接时触发
  socket.on('disconnect',function(){
    console.log('连接已断开')
  })  
}

//登录后的操作
function login(arr){
  $("#login").html("退出");
  $("#username").html(myName).show();
  $("#name").hide();
  arr = arr.map(function(item){
    return `
    <div class="user heMsg" user-id="${item.id}">
      <a href="javascript:;" class="headImg">
        <span class="info_num"></span>
        <img src="a.png" alt="" style="height: 100%;width: 100%;">
      </a>
      <div class="infocont">${item.name}</div>
    </div>   
    `
  })
  $("#user").html(arr.join(""));
  $("#h5").html("五湖四海群("+(arr.length+1)+")");
}

//点击登录或退出
$("#login").click(function(){
  if(this.innerHTML == '退出'){
    socket.close();
    this.innerHTML = '登录';
    $('#user').html('');
    $("#msgBox").html('');
    $('#username').hide();
    $("#name").show();
  }else if(this.innerHTML == '登录'){
    myName = $.trim($("#name").val());
    if(myName != ''){
      var user = { name:myName};
      link(user);
      console.log(333)
    }else{
      alert("请输入名字");
      $("#name").focus();
    }
  }
  this.innerHTML == '连接中...';
})

//消息渲染函数
function msgTPL(data,flag){    console.log(data.type,66666666)
  try{
    var blob = new Blob([data.content], { type: data.type });
    var url = URL.createObjectURL(blob);
  }catch(er){
    var url = null;
  }

  if(data.type.indexOf('image') != -1){   //图片
    var con = '<img class="sf_img" src="'+url+'">';
  }else if(data.type.indexOf('video') != -1){
    var con = '<video controls="controls" src="'+url+'"></video>';
  }else if(data.type.indexOf('audio') != -1){
    var con = '<audio controls="controls" src="'+url+'"></audio>';
  }else if(data.type != 'utf8'){
    var con = '<a href="'+url+'" target="_blank">'+data.fileName+'</a>';
  }else{
    var con = data.content;
  }
  var html = `
    <div class="${flag?'heMsg':'myMsg'}">
      <div class="msg-list-name">${data.fromName}</div>
      <a href="javascript:;" class="headImg">
        <img src="a.png" alt="" style="height: 100%;width: 100%;">
      </a>
      <span class="jiantou"></span>
      <div class="infocont">${con}</div>
    </div>
  `;
  return html;
}

//发送消息
$("#send").click(function(){
  if(!socket){
    alert("请先登录!")
    return;
  }
  var text = $.trim($("#text").html());
  if(text!=''){
    var data = {
      content:text,
      to:nowId,
      toName:nowName,
      from:myId,
      fromName:myName,
      type:'utf8'
    }
    socket.emit('msg',data,function(res){
       if(res){
          var html = msgTPL(data);
          $("#msgBox").append(html).scrollTop(100000);
          localStorage.setItem(myId+'-'+nowId,$('#msgBox').html());
          $("#text").html('');
          console.log(data,'发送成功！')
       }
    })
  }
})

//发送文件
function sendFile(t){
  if(!socket){
    alert("请先登录!")
    return;
  }
  var f = t.files[0];
  var data = {
    content:f,
    to:nowId,
    toName:nowName,
    from:myId,
    fromName:myName,
    type:f.type,
    fileName:f.name
  }  
  socket.emit('msg',data,function(res){
    var html = msgTPL(data);
    $("#msgBox").append(html).scrollTop(100000);
    localStorage.setItem(myId+'-'+nowId,$('#msgBox').html());
  });
  t.value = '';
  $('#text').html("");
}

//左侧人员点击
$("#userBox").on('click','.heMsg',function(){
  $("#userBox").find('.heMsg').removeClass('active');
  $(this).addClass('active');
  $(this).find('.info_num').hide();
  var id = $(this).attr("user-id");
  nowId = id;
  nowName = $(this).find(".infocont").text();
  $("#h5").html(nowName);
  var html = localStorage.getItem(myId+'-'+id);
  $("#msgBox").html(html).delay(100).scrollTop(100000);
})


//时间格式化函数
function timeF(time){
  var d = time? new Date(time) : new Date();
  var month = d.getMonth() + 1;
  month = month < 10 ? '0'+month : month;
  var arr = d.toString().split(' ');
  return arr[3]+'-'+month+'-'+arr[2]+' '+arr[4];
}

//点击图片查看
var lookimg = $("#lookimg").hide().css("background","#000");
$("#msgBox").on('click','.sf_img',function(){
  var url = this.src;
  lookimg.fadeIn().find('img').attr("src",url);  
  // 可缩放
  // $("[name=viewport]").attr('content','width=device-width,initial-scale=1,user-scalable=yes');
})
lookimg.click(function(){
  // $("[name=viewport]").attr('content','width=device-width,initial-scale=1,maximum-scale=1.0;user-scalable=no');
  lookimg.fadeOut();
})
</script>
</body>
</html>
